package com.yuexiang.melodyhub.user.aop;

import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.exception.UnAccessDeniedException;
import com.yuexiang.melodyhub.common.valid.HasRoles;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Aspect
@Component
public class HasRolesAspect {

    @Around("@annotation(hasRoles)")
    public Object hasRoles(ProceedingJoinPoint joinPoint, HasRoles hasRoles) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        List<String> roles = Arrays.asList(Objects.requireNonNull(attributes.getRequest().getHeader(BizConstant.HEADER_ROLES).split(",")));
        if (roles.stream().noneMatch(Arrays.asList(hasRoles.roles().split(","))::contains))
            throw new UnAccessDeniedException();
        return joinPoint.proceed();
    }

}
